package com.qinsheng.domain.strategy.service.armory;

import com.qinsheng.domain.strategy.model.entity.StrategyAwardEntity;
import com.qinsheng.domain.strategy.model.entity.StrategyEntity;
import com.qinsheng.domain.strategy.model.entity.StrategyRuleEntity;
import com.qinsheng.domain.strategy.repository.IStrategyRepository;
import com.qinsheng.types.common.Constants;
import com.qinsheng.types.enums.ResponseCode;
import com.qinsheng.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;

/**
 * ClassName: StrategyArmory
 * Description: 策略装配库，负责初始化策略计算
 *
 * @Author: qinsheng1900
 * @Create 2025/2/21 14:39
 * @Version 1.0
 */
@Slf4j
@Service
public class StrategyArmoryDispatch implements IStrategyArmory, IStrategyDispatch {

    @Resource
    private IStrategyRepository repository;

    @Override
    public boolean assembleLotteryStrategy(Long strategyId) {
        //1.查询策略配置
        List<StrategyAwardEntity> strategyAwardEntities =  repository.queryStrategyAwardList(strategyId);

        //2.装配奖品库存【用于decr扣减库存使用】
        for(StrategyAwardEntity strategyAward : strategyAwardEntities) {
            Integer awardId = strategyAward.getAwardId();
            Integer awardCount = strategyAward.getAwardCount();
            cacheStrategyAwardCount(strategyId, awardId, awardCount);
        }

        //1.1.初始化策略抽奖表
        assembleLotteryStrategy(String.valueOf(strategyId),strategyAwardEntities);

        //2.权重策略配置 - 使用与 rule_weight 权重规则配置
        StrategyEntity strategyEntity = repository.queryStrategyEntityByStrategyId(strategyId);
        String ruleWeight = strategyEntity.getRuleWeight();
        //没有配置规则
        if(null == ruleWeight) return true;
        //配置了，到sql中查询具体的设置：6000,102,103,104,105,106,107,108,109
        StrategyRuleEntity strategyRuleEntity = repository.queryStrategyRule(strategyId,ruleWeight);
        if(null == strategyRuleEntity){
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(),ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
        }
        Map<String, List<Integer>> ruleWeightValuesMap = strategyRuleEntity.getRuleWeightValues();
        //6000,4000这种
        Set<String> keys = ruleWeightValuesMap.keySet();
        for (String key : keys) {
            List<Integer> ruleWeightValues = ruleWeightValuesMap.get(key);
            ArrayList<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntities);
            strategyAwardEntitiesClone.removeIf(entity -> !ruleWeightValues.contains(entity.getAwardId()));

            assembleLotteryStrategy(String.valueOf(strategyId).concat("_").concat(key), strategyAwardEntitiesClone);
        }
        return true;
    }

    @Override
    public boolean assembleLotteryStrategyByActivityId(Long activityId) {
        Long strategyId =  repository.queryStrategyIdByActivityId(activityId);
        return assembleLotteryStrategy(strategyId);
    }

    private void cacheStrategyAwardCount(Long strategyId, Integer awardId, Integer awardCount) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        repository.cacheStrategyAwardCount(cacheKey, awardCount);
    }

    /**
     * 对策略抽奖表的装配
     * @param key
     * @param strategyAwardEntities
     */
    public void assembleLotteryStrategy(String key, List<StrategyAwardEntity> strategyAwardEntities){
        //1.获取最小概率值
        BigDecimal minAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);

        //2.获取概率总和
        BigDecimal totalAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        //换种方法，me
        int baseNumber = minAwardRate.stripTrailingZeros().scale();
        BigDecimal rateRange = totalAwardRate.movePointRight(baseNumber);


        //3.获取概率总范围 100 / 0.01，1万个
        //BigDecimal rateRange = totalAwardRate.divide(minAwardRate,0, RoundingMode.CEILING);

        //4.随机填充奖品
        List<Integer> strategyAwardSearchRateTables = new ArrayList<>(rateRange.intValue());
        for (StrategyAwardEntity strategyAward : strategyAwardEntities) {
            Integer awardId = strategyAward.getAwardId();
            BigDecimal awardRate = strategyAward.getAwardRate();
            //计算出每个概率值（奖品档次）需要存放到查询表的数量，循环填充
//            for (int i=0; i < rateRange.multiply(awardRate).setScale(0,RoundingMode.CEILING).intValue(); i++) {
//                strategyAwardSearchRateTables.add(awardId);
//            }
            for (int i=0; i < awardRate.movePointRight(baseNumber).intValue(); i++) {
                strategyAwardSearchRateTables.add(awardId);
            }
        }
        //5，乱序奖品（strategyAwardSearchRateTables存的是奖品ID）
        Collections.shuffle(strategyAwardSearchRateTables);

        //6.把奖品和编号存到hash表中
        HashMap<Integer, Integer> shuffleStrategyAwardSearchRateTables = new HashMap<>();
        for (int i = 0; i < strategyAwardSearchRateTables.size(); i++) {
            shuffleStrategyAwardSearchRateTables.put(i, strategyAwardSearchRateTables.get(i));
        }

        //7.存储到redis中
        repository.storeStrategyAwardSearchRateTables(key, rateRange, shuffleStrategyAwardSearchRateTables);
    }

    @Override
    public Integer getRandomAwardId(Long strategyId) {
        //根据strategyId 返回奖品id
        int rateRange = repository.getRateRange(strategyId);
        //通过生成的随机值，获取概率值奖品查找表的结果
        return repository.getStrategyAwardAssemble(String.valueOf(strategyId), new SecureRandom().nextInt(rateRange));
    }

    @Override
    public Integer getRandomAwardId(Long strategyId, String ruleWeightValue) {
        String key = String.valueOf(strategyId).concat("_").concat(ruleWeightValue);
        //根据strategyId 返回奖品id
        int rateRange = repository.getRateRange(key);
        //通过生成的随机值，获取概率值奖品查找表的结果
        return repository.getStrategyAwardAssemble(key, new SecureRandom().nextInt(rateRange));
    }

    @Override
    public Boolean subtractionAwardStock(Long strategyId, Integer awardId) {
        String cachekey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        return repository.subtractionAwardStock(cachekey);
    }
}
